from flask import Blueprint, current_app, request
from flask_mail import Message
from applications.extensions import mail
from applications.common.utils.http import success_api, fail_api
from applications.common.utils.validate import xss_escape
import threading

mail_send = Blueprint('mailSend', __name__, url_prefix='/mail/send')


@mail_send.post('/qrcode')
def send_qrcode():
    req = request.json
    qrcode_path = xss_escape(req.get("qrcode_path"))
    message = Message(
        subject='自动发送-微信公众号爬虫管理员二维码登录',
        recipients=['1531982951@qq.com'],
        body="请在两分钟内完成验证-二维码以附件形式发送",
    )
    app = current_app._get_current_object()
    with app.open_resource(qrcode_path) as fp:
        message.attach("qrcode.jpg", "image/jpg", fp.read())
    # 发送
    thread = threading.Thread(target=async_send_mail, args=(app, message))
    thread.start()
    return success_api(msg="成功发送")


def async_send_mail(app,msg):
    with app.app_context():
        mail.send(message=msg)

def send_email_captcha(message):
    app = current_app._get_current_object()
    thread = threading.Thread(target=async_send_mail, args=(app, message))
    thread.start()


